<?php
namespace EasyShortUrl\Http\Controller;

use EasyShortUrl\Facades\ShortUrl;
use Illuminate\Support\Facades\Cache;

class ShortUrlController extends \App\Http\Controllers\Controller
{
    public function redirectLongUrl($code = '')
    {
        try {
            if (config('shorturl.esu_cache_open') === '1') {

                $key = "mapping_code_and_long_url_".$code;
                if(Cache::has($key)){
                    return redirect(Cache::get($key));
                }
                $url = ShortUrl::toLong($code);
                Cache::forever($key,$url);
                return redirect($url);
            }
            $url = ShortUrl::toLong($code);
            if (config('shorturl.esu_cache_open') !== '1') {
                ShortUrl::requestNum($code);
            }
            return redirect($url);
        } catch (\Exception $e) {
            header("HTTP/1.1 404 Not Found");
            exit;
        }
    }
}
